import { login, logout, getInfo } from '@/api/api'
import { getTokenKey, setTokenKey, removeTokenKey, getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import md5 from 'js-md5'

const state = {
  token: getToken(getTokenKey()),
  data: {},
  name: '',
  avatar: '',
  roles: [],
  permissions: []
}

const mutations = {
  SET_DATA: (state, data) => {
    state.data = data
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, id } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: md5(password), id: id }).then(response => {
        const { data } = response
        if (data) {
          commit('SET_TOKEN', data.token)
          setTokenKey(data.tokenName)
          setToken(data.tokenName, data.token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, dispatch }, status) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          reject('身份认证失败,请重新授权')
        }
        commit('SET_DATA', data)
        commit('SET_ROLES', data.roleCodes)
        commit('SET_PERMISSIONS', data.permissions)
        commit('SET_NAME', data.name)
        commit('SET_AVATAR', data.avatar)
        // 若status为true，代表信息编辑
        if (!status) {
          // 将返回的菜单数组处理为路由格式；注意，跨文件调用action必须加上第三个参数{root: true}，被坑惨了
          dispatch('permission/generateRoutes', data.menus, { root: true }).then(res => {
          // 确认刷新无过期情况
            commit('app/ISMESSAGEBOX', true, { root: true })
            resolve(res)
          })
        } else resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_DATA', {})
        removeToken(getTokenKey())
        removeTokenKey()
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_DATA', {})
      removeToken(getTokenKey())
      removeTokenKey()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
